package hy.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@MapperScan("hy.mapper")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyCfg extends WebSecurityConfigurerAdapter{
    @Autowired
    UserDetailsService us;
    @Autowired
    PasswordEncoder pe;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(us).passwordEncoder(pe);
    }
    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login.html")//修改默认登录界面为login.html,否则使用默认界面
                .loginProcessingUrl("/user/login")//登录的提交路径，无需人工实现其handler,只用于login表单的post提交路径
                .defaultSuccessUrl("/success.html").permitAll()//登录成功后的跳转路径，不登录不能直接访问
                .and().authorizeRequests().antMatchers("/hello","/test").permitAll()//这些路径无需认证，直接访问,注意是localhost/test,而不是localhost/test/
                .and().authorizeRequests().antMatchers("/index").hasAuthority("admin")
                //这里如果是hasAuthority,则认证角色必须同时拥有下面两个权限才有权访问，而any则表示有一个就能访问
                .and().authorizeRequests().antMatchers("/a1").hasAnyAuthority("admin","abc")
                .anyRequest().authenticated()//剩下的统统要认证
                .and().csrf().disable();//必须关闭csrf防护
        http.exceptionHandling().accessDeniedPage("/error.html");
        http.logout().logoutUrl("/log").logoutSuccessUrl("/logoutSuc").permitAll();
    }
}
